import java.io.*;
import java.net.*;
import java.util.*;
import java.security.Security;
import java.security.Provider;
import javax.net.ssl.*;

import javax.servlet.*;
import javax.servlet.http.*;

import local.util.MyPrint;
import local.util.MyStringFormat;

public class GetIndexDataServlet  extends HttpServlet {    

    private String url = null;
    private String urlReturnString = null;
    private String startString = null;
    private String endString = null;
    private static boolean save = false;
   
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws IOException, ServletException
    {
	response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
	out.println("<title>Stock chart index</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(printIndexDataHead());
        out.println(printVector(getIndexData(), 5));

        out.println("</body>");
        out.println("</html>");
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
	doPost(request, response);
    }

    private Vector vInput= new Vector(10);

    private Hashtable dataHashTable = new Hashtable();

    public Vector getIndexData () {

	String my_url     = "http://finance.yahoo.com/m0";;
	Vector tempV = new Vector ();
	Hashtable tempH = new Hashtable ();

	setUrl(my_url);
	connectToHttpUrl();

	tempV = putInVectorByLine(getUrlReturnString());

	setStartString("Bulletin Board");
	setEndString("ADVERTISEMENT");

	tempV = selectUsefulInfo(tempV);
	return tempV;
    }

    public String printIndexDataHead () {
	DateAndTime dt = new DateAndTime();
	return("<TABLE width = '100%'><TR><TD width='20%' align='right'>"+dt.getCurrentTime()+
	       "</TD><TD width='20%'  align='right'>NYSE</TD>"+
	       "<TD width='20%' align='right'>AMEX</TD><TD width='20%' align='right'>Nasdaq</TD>"+
	       "<TD width='20%' align='right'>Bulletin Board</TD></TR>");
    }

    public void setUrl (String url_in) {
	url = url_in;
    }

    public String getUrl () {
	return url;
    }

    public void setUrlReturnString (String url_return_string) {
	urlReturnString = url_return_string;
    }

    public String getUrlReturnString () {
	return urlReturnString;
    }

    public void setStartString (String start_string) {
	startString = start_string;
    }

    public void setEndString (String end_string) {
	endString = end_string;
    }

    public void connectToHttpUrl () {

	String urlAddress = getUrl();
	String url_return_string;

	HttpURLConnection httpConnection = null;
	String up;

	try {            
	    URL url = new URL (urlAddress);  
	    try {                
		httpConnection = (HttpURLConnection)url.openConnection();                
		httpConnection.setDoOutput(false);                
		httpConnection.connect();                
		
		System.out.println("Connection Code and Message:" + 
				   httpConnection.getResponseCode() + 
				   " - " + httpConnection.getResponseMessage()+"\n");
		
		BufferedReader in = new BufferedReader(new InputStreamReader
		    (httpConnection.getInputStream()));

		StringBuffer buff= new StringBuffer("");

		url_return_string = in.readLine();

		while (url_return_string != null) {
		    buff.append(url_return_string);
		    url_return_string = in.readLine();
		}

		in.close();            

		url_return_string = buff.toString();
		
		url_return_string = url_return_string.replaceAll("\n","");
		url_return_string = url_return_string.replaceAll("\t","");
		url_return_string = url_return_string.replaceAll("&nbsp;","");
		
		url_return_string = url_return_string.replaceAll(">",">\n");
		url_return_string = url_return_string.replaceAll("</","\n</");

		url_return_string = url_return_string.replaceAll("Advancing Issues","Up Issues");
		url_return_string = url_return_string.replaceAll("Declining Issues","Down Issues");

		setUrlReturnString(url_return_string);

	    } catch (IOException ioe) {                
		System.out.println(ioe.getMessage());  
		System.exit(1);            
	    }        
	} catch (MalformedURLException mue) {            
	     System.out.println(mue.getMessage());            
	    System.exit(1);        
	} catch (Exception e) {            
	    e.printStackTrace();            
	    System.exit(1);        
	}    
    }

    
    public Vector putInVectorByLine (String input) {

	Vector v = new Vector (10);
	String element = "";
	StringTokenizer tokens = new StringTokenizer(input,"\n");
	while (tokens.hasMoreTokens()) {
	    element = (String)tokens.nextToken();
	    if (element != null) {
		v.addElement(element.trim());
	    }
	}
	
	return v;
    }
    
    public Vector selectUsefulInfo (Vector v_in) {
	Vector v_out = new Vector (10);
	String text = "";
	Enumeration penum = v_in.elements();
       
	while ( penum.hasMoreElements()) {

	    text = (String)penum.nextElement();
	    if (text.startsWith(startString)) {
		break;
	    }
	}
	
	while ( penum.hasMoreElements() ) {
	    text = (String)penum.nextElement();
	    if (text.startsWith(endString)) {
		break;
	    }
	    if (!(text.startsWith("<") ||
		  text.startsWith("+") || 
		  text.startsWith("to<"))) {
		if(!text.equals(""))
		v_out.addElement(text);
	    }
	}
	
	return v_out;
    }

    public StringBuffer printVector( Vector inputV, int colum_number) {

	int m = colum_number;
	int n =0;
	StringBuffer s_bf = new StringBuffer();
	String temp = null;
	MyStringFormat sf = new MyStringFormat();
	Enumeration penum = inputV.elements();
	s_bf.append("<TR>");
	while ( penum.hasMoreElements()) { 
	    temp = (String)(penum.nextElement());
	    if (temp.equals("Total Volume")) {
		s_bf.append("<BR>");
	    }

	    s_bf.append("<TD align='right'>"+temp+"</TD>");
	    n++;
	    if (n%m==0) {
		s_bf.append("</TR>");
	    }
	}
	return (s_bf.append("</TABLE>"));
    }
}







